//
//  LWRefreshControl.swift
//  Microblog
//
//  Created by Roman on 17/1/12.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit
enum LWRefreshStatue: Int {
    case Normal
    case Arleady
    case Refreshing
}
private let refreshControllerHeight: CGFloat = 60
class LWRefreshControl: UIControl {

    //定义枚举的默认状态
    var statue: LWRefreshStatue = .Normal {
        didSet{
            switch statue {
            case .Normal:
                textLabel.text = "下拉刷新"
                arrowIcon.isHidden = false
                IndicatorView.stopAnimating()
                UIView.animate(withDuration: 0.24, animations: {
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                if oldValue == .Refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        
                        let insertTop = self.scrollView?.contentInset.top ?? 0
                        self.scrollView?.contentInset = UIEdgeInsetsMake(insertTop - refreshControllerHeight, 0, 0, 0)
                    })
                }
                
                
                //print("默认状态")
            case .Arleady:
                textLabel.text = "准备刷新-!!!!!-----"
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowIcon.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                //print("准备状态")
            case .Refreshing:
                textLabel.text = "正在起飞......."
                arrowIcon.isHidden = true
                IndicatorView.startAnimating()
                //print("刷新状态")
                //正在刷新,应该触发相应的事件
                sendActions(for: .valueChanged)
                //悬停效果
                UIView.animate(withDuration: 0.25, animations: {
                    
                    let insertTop = self.scrollView?.contentInset.top ?? 0
                    self.scrollView?.contentInset = UIEdgeInsetsMake(refreshControllerHeight + insertTop, 0, 0, 0)
                })
                
            
            }
        }
    }
    func endRefreshing() {
        //修改状态,延迟执行
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute:{
            self.statue = .Normal
        })
        
    }
        
    
   //自定义下拉刷新控件
    override init(frame: CGRect) {
        
        let frame = CGRect(x: 0, y: -refreshControllerHeight, width: ScreenWidth, height: refreshControllerHeight)
//        self.backgroundColor = UIColor.red
        super.init(frame: frame)
        setupUI()
        self.backgroundColor = UIColor.orange
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

   private func setupUI() {
    addSubview(textLabel)
    addSubview(IndicatorView)
    addSubview(arrowIcon)
    
    //设置布局约束,要以文字作为中心
    textLabel.snp.makeConstraints { (make) in
        make.centerY.equalTo(self)
        make.centerX.equalTo(self).offset(10)
    }
   
    IndicatorView.snp.makeConstraints { (make) in
        make.trailing.equalTo(textLabel.snp.leading).offset(-5)
        make.centerY.equalTo(self)
    }
    arrowIcon.snp.makeConstraints { (make) in
        make.center.equalTo(IndicatorView)
    }
    
    }
    //进行下拉移动的判断,视图的生命周期方法
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let superView = newSuperview as? UIScrollView{
            //如果是UIScrollView ,就进行监听,下面写监听方法
            superView.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
            self.scrollView = superView
        }
        
    }
    
    //监听方法,不写会导致系统崩溃
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offsetY = scrollView?.contentOffset.y ?? 0
        //print(offsetY)
        if scrollView!.isDragging == true{
            //正在被拖拽
            //当完全下拉出来时候60+64 进行刷新 > 124
            if offsetY < -124 && statue == .Normal{
                //-134 < - 124
                statue = .Arleady
                
            }else if statue == .Arleady && offsetY > -124  {
                
                statue = .Normal
                
            }

        }else{
            if statue == .Arleady {
                //改为正在刷新
                statue = .Refreshing
            }
        }       
    }
    
    
    //懒加载控件
    //向下的箭头
    lazy var arrowIcon = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    
    //文字
    lazy var textLabel = UILabel(text: "下拉刷新", fontSize: 12, textColor: UIColor.black)
    
    //刷新的样式
    lazy var IndicatorView :UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    //记录父视图对象
    var scrollView: UIScrollView?
    
    //移除监听
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
